﻿using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Serialization;

namespace _00_数据保存
{
    public partial class Form1 : Form
    {
        ///创建随机数对象
        Random rd = new Random();
        //绑定数据源
        BindingList<Point> points = new BindingList<Point>();


        public Form1()
        {
            InitializeComponent();
            //绑定数据源
            this.dataGridView1.DataSource = points;
        }

        /// <summary>
        /// 窗体关闭的时候，保存选择的索引
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //获取当前选择的选卡索引
            int index = this.tabControl1.SelectedIndex;
            //写入INI配置文件
            INI.WritePrivateProfileString("界面配置", "选项卡索引", index.ToString(), "./界面配置.ini");

            //写入CSV配置文件的路径
            INI.WritePrivateProfileString("界面配置", "CSV路径", this.textBox1.Text, "./界面配置.ini");

            //写入Excel配置文件的路径
            INI.WritePrivateProfileString("界面配置", "Excel路径", this.textBox2.Text, "./界面配置.ini");

            //写入XML配置文件的路径
            INI.WritePrivateProfileString("界面配置", "XML路径", this.textBox3.Text, "./界面配置.ini");

            //写入JSON配置文件的路径
            INI.WritePrivateProfileString("界面配置", "JSON路径", this.textBox4.Text, "./界面配置.ini");

        }

        /// <summary>
        /// 窗体加载的时候，读取INI配置文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Shown(object sender, EventArgs e)
        {
            //读取INI配置文件
            string index = INI.ContentValue("界面配置", "选项卡索引", "./界面配置.ini");
            //设置选项卡索引
            this.tabControl1.SelectedIndex = int.Parse(index);

            //读取CSV配置文件的路径
            string csvPath = INI.ContentValue("界面配置", "CSV路径", "./界面配置.ini");
            //设置文本框的值
            this.textBox1.Text = csvPath;

            //读取Excel配置文件的路径
            string excelPath = INI.ContentValue("界面配置", "Excel路径", "./界面配置.ini");
            //设置文本框的值
            this.textBox2.Text = excelPath;

            //读取XML配置文件的路径
            string xmlPath = INI.ContentValue("界面配置", "XML路径", "./界面配置.ini");
            //设置文本框的值
            this.textBox3.Text = xmlPath;

            //读取JSON配置文件的路径
            string jsonPath = INI.ContentValue("界面配置", "JSON路径", "./界面配置.ini");
            //设置文本框的值
            this.textBox4.Text = jsonPath;

        }
        /// <summary>
        /// 随机数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            for (int i = 1; i < 20; i++)
            {
                Point point = new Point(rd.Next(0,100), rd.Next(0, 100), rd.Next(0, 100),"节点-"+i);
                //添加节点
                points.Add(point);
            }

        }
        /// <summary>
        /// CSV保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            //添加一个集合用来存储CSV行数据
            List<string[]> csvData = new List<string[]>();

            //定义CSV文件路径
            string csvPath = this.textBox1.Text;

            //创建CSV表格的表头
            string[] header = new string[] {  "节点名称", "X坐标", "Y坐标", "Z坐标"};
            //添加到集合中
            csvData.Add(header);

            //CSV表格的内容，添加到集合中
            foreach (var item in points)
            {
                csvData.Add(new string[] { item.Name, item.X.ToString(), item.Y.ToString(), item.Z.ToString() });
            }

            //写入CSV文件
            //参数一：CSV文件路径
            //参数二：CSV文件内容
            //参数三：是否追加 false表示覆盖,true表示追加
            CSV.WriteCSV(csvPath, csvData, false);

            //提示用户
            MessageBox.Show("CSV文件保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        /// <summary>
        /// CSV读取
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            //定义一下CSV文件路径
            string csvPath = this.textBox1.Text;

            //读取CSV文件
            List<string[]> csvData = CSV.ReadCSV(csvPath);

            //清空数据源
            points.Clear();

            //跳过表头，从第二行开始读取
            for (int i = 1; i < csvData.Count; i++)
            {
                //添加节点
                points.Add(new Point(int.Parse(csvData[i][1]), int.Parse(csvData[i][2]), int.Parse(csvData[i][3]), csvData[i][0]));
            }

        }

        /// <summary>
        /// Excel保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            //获取Excel文件路径
            string excelPath = this.textBox2.Text;

            //创建一个新的工作簿.Excel对象
            IWorkbook workBook = new XSSFWorkbook();

            //创建一个新的工作表,Points为工作表名称
            ISheet sheet = workBook.CreateSheet("Points");

            //创建表头
            IRow headerRow = sheet.CreateRow(0);//创建第一行
            //设置表头的单元格，列索引从0开始，逐个创建单元格并设置值
            headerRow.CreateCell(0).SetCellValue("节点名称");
            headerRow.CreateCell(1).SetCellValue("X坐标");
            headerRow.CreateCell(2).SetCellValue("Y坐标");
            headerRow.CreateCell(3).SetCellValue("Z坐标");

            //创建表格内容
            for (int i = 0; i < points.Count; i++)
            {
                //创建行
                IRow row = sheet.CreateRow(i + 1);//从第二行开始
                //设置单元格的值
                row.CreateCell(0).SetCellValue(points[i].Name);
                row.CreateCell(1).SetCellValue(points[i].X);
                row.CreateCell(2).SetCellValue(points[i].Y);
                row.CreateCell(3).SetCellValue(points[i].Z);
            }

            //将工作簿保存到指定路径
            using (FileStream fs = new FileStream(excelPath,FileMode.Create,FileAccess.Write))
            {
                workBook.Write(fs);
            }

            //提示用户
            MessageBox.Show("Excel文件保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }
        /// <summary>
        /// 读取Excel文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            //获取Excel文件路径
            string excelPath = this.textBox2.Text;
            //创建一个新的工作簿.Excel对象
            using (FileStream fs = new FileStream(excelPath,FileMode.Open,FileAccess.Read))
            {
                //创建一个新的工作簿
                IWorkbook workBook = new XSSFWorkbook(fs);

                //获取第一个工作表
                ISheet sheet = workBook.GetSheetAt(0);

                //清空数据源
                points.Clear();

                //跳过表头，从第二行开始读取
                for (int i = 1; i <= sheet.LastRowNum; i++)
                {
                    //获取行
                    IRow row = sheet.GetRow(i);
                    //获取单元格的值
                    string name = row.GetCell(0).StringCellValue;
                    int x = (int)row.GetCell(1).NumericCellValue;
                    int y = (int)row.GetCell(2).NumericCellValue;
                    int z = (int)row.GetCell(3).NumericCellValue;
                    //添加节点
                    points.Add(new Point(x, y, z, name));
                }
            }
        }
        /// <summary>
        /// xml保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button8_Click(object sender, EventArgs e)
        {
            //定义XML文件路径
            string xmlPath = this.textBox3.Text;

            //创建XML序列化器
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(BindingList<Point>));

            //创建文件流
            using (FileStream fs = new FileStream(xmlPath, FileMode.Create, FileAccess.Write))
            {
                //序列化数据
                xmlSerializer.Serialize(fs, points);
            }

            //提示用户
            MessageBox.Show("XML文件保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }
        /// <summary>
        /// 读取XML文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button7_Click(object sender, EventArgs e)
        {
            //定义XML文件路径
            string xmlPath = this.textBox3.Text;

            //创建XML序列化器
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(BindingList<Point>));

            //创建文件流
            using (FileStream fs = new FileStream(xmlPath, FileMode.Open, FileAccess.Read))
            {
                //反序列化数据
                BindingList<Point> points1 = (BindingList<Point>)xmlSerializer.Deserialize(fs);
                //清空数据源
                points.Clear();
                //添加数据到数据源
                foreach (var item in points1)
                {
                    points.Add(item);
                }
            }

        }
        /// <summary>
        /// JSON格式保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button11_Click(object sender, EventArgs e)
        {
            //获取JSON文件路径
            string jsonPath = this.textBox4.Text;
            //将数据源转换为JSON格式
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(points);
            //将JSON格式数据写入文件
            File.WriteAllText(jsonPath, json);
            //提示用户
            MessageBox.Show("JSON文件保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }
        /// <summary>
        /// JSON格式读取
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button10_Click(object sender, EventArgs e)
        {
            //获取JSON文件路径
            string jsonPath = this.textBox4.Text;
            //读取JSON格式数据
            string json = File.ReadAllText(jsonPath);
            //将JSON格式数据转换为数据源
            BindingList<Point> points1 = Newtonsoft.Json.JsonConvert.DeserializeObject<BindingList<Point>>(json);
            //清空数据源
            points.Clear();
            //添加数据到数据源
            foreach (var item in points1)
            {
                points.Add(item);
            }

        }
    }
}
